<template>
  <div class="app-container">
    <el-row :gutter="20" class="toolbar" type="flex" justify="space-between">
      <!-- 左侧组合 -->
      <el-col :span="16">
        <el-row :gutter="15">
          <el-col :span="10">
            <el-input
                v-model="searchKey"
                placeholder="输入用户名、昵称或手机号搜索"
                @keyup.enter.native="handleSearch">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
          </el-col>
        </el-row>
      </el-col>

      <!-- 右侧按钮 -->
      <el-col :span="8" class="text-right">
        <el-button type="primary" @click="handleCreate">添加用户</el-button>
      </el-col>

    </el-row>
    <!-- 数据表格 -->
    <el-table
        :data="userList"
        border
        stripe
        style="width: 100%"
        class="data-table">
      <el-table-column
          type="index"
          label="序号"
          width="60"
          align="center">
      </el-table-column>

      <el-table-column
          prop="username"
          label="用户名"
          min-width="150">
      </el-table-column>

      <el-table-column
          prop="nickname"
          label="昵称"
          min-width="150">
      </el-table-column>

      <el-table-column
          prop="mobile"
          label="手机号"
          min-width="150">
      </el-table-column>

      <el-table-column
          prop="creator"
          label="创建人"
          width="120">
      </el-table-column>

      <el-table-column
          prop="createTime"
          label="创建时间"
          width="180">
      </el-table-column>


      <el-table-column
          label="操作"
          width="200"
          align="center">
        <template #default="{row}">
          <el-button
              type="text"
              size="small"
              @click="handleConfig(row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="500px"
        @close="resetForm">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="登录账号" prop="username" required>
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" required>
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" value="male"></el-option>
            <el-option label="女" value="female"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" required>
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" required>
          <el-input type="password" v-model="form.confirmPassword"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>
import {querySysUserPage, delUser, createUser} from '@/api/sys-user-manage'
import {rsaEncryptWithDefaultKey} from "@/utils/rsa";

export default {
  data() {
    return {
      selectedApp: '',
      searchKey: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userList: [],
      dialogVisible: false,
      form: {
        username: '',
        nickname: '',
        mobile: '',
        gender: '',
        email: '',
        password: '',
        confirmPassword: '',
        avatar: '',
        roleIds: new Set()
      },
      rules: {
        username: [
          {required: true, message: '请输入登录账号', trigger: 'blur'},
          {min: 6, max: 30, message: '账户长度只能为6~30个字符', trigger: 'blur'},
          {pattern: /^[a-zA-Z0-9]{6,30}$/, message: '账户名只能由数字或字母组成', trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {pattern: /^1[3-9]\d{9}$/, message: '手机号错误', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请确认密码', trigger: 'blur'}
        ],
        email: [
          {type: 'email', message: '邮箱格式错误', trigger: 'blur'}
        ]
      }
    }
  },
  mounted() {
    this.loadAppData()
  },
  watch: {
    'form.password'(newVal, oldVal) {
      console.log(`Password changed from ${oldVal} to ${newVal}`);
    },
    'form.confirmPassword'(newVal, oldVal) {
      console.log(`Confirm Password changed from ${oldVal} to ${newVal}`);
    }
  },
  methods: {
    // 加载数据方法
    async loadAppData() {
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          keywords: this.searchKey,
        }

        const {data} = await querySysUserPage(params)
        this.userList = data.records
        this.total = data.total
        this.currentPage = data.current
        this.pageSize = data.size
      } catch (error) {
        console.error('数据加载失败:', error)
      }
    },
    // 修改后的处理方法
    handleSearch() {
      this.currentPage = 1 // 搜索时重置到第一页
      this.loadAppData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadAppData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadAppData()
    },
    async handleConfig(row) {
      delUser({id: row.id}).then(res => {
        this.loadAppData()
      })
    },
    handleCreate() {
      this.dialogVisible = true;
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    submitForm() {
      // 使用JSON.stringify打印对象的具体内容
      console.log('密码:', this.form.password)
      console.log('确认密码:', this.form.confirmPassword)
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.password !== this.form.confirmPassword) {
            this.$message.error('密码和确认密码不一致');
            return;
          }
          const userData = {
            username: this.form.username,
            nickname: this.form.nickname,
            mobile: this.form.mobile,
            sex: this.form.gender === 'male' ? 1 : (this.form.gender === 'female' ? 2 : null),
            email: this.form.email,
            password: rsaEncryptWithDefaultKey(this.form.password), // 这里假设密码已经经过加密处理
            confirmPassword: rsaEncryptWithDefaultKey(this.form.confirmPassword),
            avatar: this.form.avatar,
            //目前版本固定为管理员
            roleIds: ['1778237581039464450']
          };
          console.log(userData)
          console.log("请求体", userData)
          createUser(userData).then(() => {
            this.$message.success('用户创建成功');
            this.dialogVisible = false;
            this.resetForm();
            this.loadAppData();
          }).catch(error => {
            console.error('用户创建失败:', error);
          });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    }
  }
}
</script>

<style scoped>

/* 新增样式 */
.el-dialog__body {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-textarea {
  resize: vertical;
}

.toolbar {
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
}

.data-table {
  margin-top: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.text-right {
  text-align: right;
}

.detail-dialog .el-form-item {
  margin-bottom: 15px;
}

.detail-dialog .el-form-item span {
  font-weight: bold;
  color: #333;
}

.detail-dialog .dialog-footer {
  text-align: right;
  padding: 10px 0;
}

.detail-dialog .el-dialog__body {
  padding: 20px 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
}
</style>

